package logrushook

import (
	"jgt-wallet/src/logger"
	"jgt-wallet/src/schema"
	"jgt-wallet/src/service/mongo"
	"jgt-wallet/src/util"

	"github.com/globalsign/mgo"
	"github.com/sirupsen/logrus"
)

// NewMongoHook 创建mongo钩子
func NewMongoHook(db *mongo.DB) *MongoHook {
	return &MongoHook{db}
}

// MongoHook mongo日志钩子
type MongoHook struct {
	db *mongo.DB
}

// Exec 写入日志到mongo
func (a *MongoHook) Exec(entry *logrus.Entry) error {
	cName := "oper_log"
	id, err := a.db.IncrID(cName)
	if err != nil {
		return err
	}

	item := &schema.LogManage{
		ID:       id,
		RecordID: util.UUID(),
		Level:    entry.Level.String(),
		Message:  entry.Message,
		Created:  entry.Time.Unix(),
	}

	if data := entry.Data; data != nil && len(data) > 0 {
		if v, ok := data[logger.TypeField]; ok && v != nil {
			item.Type = v.(string)
			delete(data, logger.TypeField)
		}

		if v, ok := data[logger.UserIDField]; ok && v != nil {
			item.Creator = v.(string)
			delete(data, logger.UserIDField)
		}

		item.Data = util.JSONMarshalToString(data)
	}

	return a.db.C(cName, func(c *mgo.Collection) error {
		return c.Insert(item)
	})
}
